"""
@Author：十
@Time：2025/9/3 10:18
@FileName：addDevice.py
@Description：
"""
import sqlite3
import sys

from PyQt5.QtCore import QObject, pyqtSignal, Qt, QPoint, QRegExp
from PyQt5.QtGui import QMouseEvent, QRegExpValidator
from PyQt5.QtWidgets import QApplication, QMessageBox, QWidget
from loguru import logger
import os

from UI.addDevice import Ui_Form
import resource.WTC_rc


class AddWindow(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(AddWindow, self).__init__()
        self.setupUi(self)

        self.parent = parent

        self.initInterface()

        self.pushButton.clicked.connect(self.insert_device_data)
        self.pushButton_close.clicked.connect(self.close)

    def showWindow(self):
        self.show()

    def initInterface(self):
        reg = QRegExp('[0-9]+$')
        validator = QRegExpValidator()
        validator.setRegExp(reg)
        self.lineEdit_sensor.setValidator(validator)

        self.setWindowFlags(Qt.FramelessWindowHint)

    def insert_device_data(self):
        validation_result = self.validate_device_input()
        if not validation_result["valid"]:
            QMessageBox.warning(self, '输入错误', validation_result["message"])
            return

        # 2. 准备数据 - 单独处理
        device_data = (
            self.lineEdit_site.text(),
            self.lineEdit_location.text(),
            self.lineEdit_device.text(),
            self.lineEdit_joints.text(),
            self.lineEdit_sensor.text()
        )
        print(f"准备插入数据: {device_data}")

        # 3. 安全执行数据库操作
        try:
            # 使用上下文管理器处理数据库连接
            with self.get_db_connection() as conn:
                try:
                    cursor = conn.cursor()
                    sql = """INSERT INTO device_db(site, location, device, joints, sensor_id)
                                VALUES (?, ?, ?, ?, ?)"""
                    cursor.execute(sql, device_data)

                    conn.commit()
                    QMessageBox.information(self, '成功', '设备数据插入成功')
                    self.clear_form_fields()

                    self.parent.Signal_Refresh_Data.emit()

                except sqlite3.Error as e:
                    conn.rollback()
                    logger.error(f"数据库操作失败: {e}")
                    QMessageBox.critical(self, '数据库错误', f'数据库操作失败: {e}')

        except IOError as e:
            logger.critical(f"数据库连接失败: {e}")
            QMessageBox.critical(self, '系统错误', '无法连接数据库，请检查数据库文件是否存在')

    # TODO:串口发送，向测温主机发送添加
    def add_device(self):
        pass

    def validate_device_input(self):
        result = {"valid": True, "message": ""}

        sensor_id = self.lineEdit_sensor.text().strip()
        if len(sensor_id) != 5:
            result["valid"] = False
            result["message"] = '请输入五位的传感器的数字ID'
            return result

        fields = [
            (self.lineEdit_site, '站点'),
            (self.lineEdit_location, '位置'),
            (self.lineEdit_device, '设备'),
            (self.lineEdit_joints, '节点')
        ]

        for field, name in fields:
            text = field.text().strip()
            if not text:
                result["valid"] = False
                result["message"] = f'请输入电缆接头所在{name}'
                return result

            # 防止SQL注入的基本检查
            if any(char in text for char in [";", "--", "/*", "*/", "'", "\""]):
                result["valid"] = False
                result["message"] = f'{name}包含非法字符'
                return result

        try:
            with self.get_db_connection() as conn:
                cursor = conn.cursor()
                cursor.execute("SELECT COUNT(*) FROM device_db WHERE sensor_id = ?", (sensor_id,))
                if cursor.fetchone()[0] > 0:
                    result["valid"] = False
                    result["message"] = '该传感器ID已被其他设备使用'
        except:
            pass  # 验证时不阻断主流程

        return result

    def get_db_connection(self):

        class DatabaseContext:
            def __init__(self, parent):
                self.parent = parent

            def __enter__(self):
                os.makedirs('db', exist_ok=True)
                self.conn = sqlite3.connect('db/WTC.db')
                return self.conn

            def __exit__(self, exc_type, exc_val, exc_tb):
                if hasattr(self, 'conn') and self.conn:
                    self.conn.close()
                return False

        return DatabaseContext(self)

    def clear_form_fields(self):
        fields = [
            self.lineEdit_sensor,
            self.lineEdit_site,
            self.lineEdit_location,
            self.lineEdit_device,
            self.lineEdit_joints
        ]
        for field in fields:
            field.clear()

    # TODO: 数据保存到表格

    def mouseMoveEvent(self, e: QMouseEvent):  # 重写移动事件
        if self._tracking:
            self._endPos = e.pos() - self._startPos
            self.move(self.pos() + self._endPos)

    def mousePressEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._startPos = QPoint(e.x(), e.y())
            self._tracking = True

    def mouseReleaseEvent(self, e: QMouseEvent):
        if e.button() == Qt.LeftButton:
            self._tracking = False
            self._startPos = None
            self._endPos = None


class SendingState(QObject):
    flag_changed = pyqtSignal(bool)

    def __init__(self):
        super().__init__()
        self._shared_flag = False

    @property
    def shared_flag(self):
        return self._shared_flag

    @shared_flag.setter
    def shared_flag(self, value):
        if self._shared_flag != value:
            self._shared_flag = value
            self.flag_changed.emit(value)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = AddWindow()
    mainWindow.show()
    sys.exit(app.exec_())
